package com.boge.common;

import com.boge.core.common.AjaxResult;
import com.boge.exception.ParamException;
import com.boge.exception.PermissionException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 如果一个类被spring管理，里面的异常在http返回的时候会被它捕捉，进行异常处理
 */
@Slf4j
/*@Component*/
public class SpringExceptionResolver implements HandlerExceptionResolver {

    //TODO:404
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {
        String url = request.getRequestURL().toString();
        //TODO:
        ModelAndView mv;
        String defaultMsg = "System error";

        if (url.endsWith(".json")) {
            //只有自定义异常才显示给用户，否则显示默认异常信息
            log.info("asassa:" + e.getMessage());
            if (e instanceof PermissionException || e instanceof ParamException) {
                log.info("ParamException:" + e.getMessage());
                AjaxResult ajaxResult = new AjaxResult(false, e.getMessage());
                mv = new ModelAndView("jsonView", ajaxResult.toMap());
            } else {
                log.error("unknow json exception, url:" + url, e);
                AjaxResult ajaxResult = new AjaxResult(false, defaultMsg);
                mv = new ModelAndView("jsonView", ajaxResult.toMap());
            }
        } else if (url.endsWith(".page")) {
            log.error("unknow page exception, url:" + url, e);
            AjaxResult ajaxResult = new AjaxResult(false, defaultMsg);
            mv = new ModelAndView("common/exception", ajaxResult.toMap());
        } else {
            log.error("unknow exception, url:" + url, e);
            AjaxResult ajaxResult = new AjaxResult(false, defaultMsg);
            mv = new ModelAndView("jsonView", ajaxResult.toMap());
        }

        return mv;
    }

}
